<template>
    <div>
      <el-container>
        <el-aside class="aside">
          <el-table
          :data="historyData"
          @row-click="handleRowClick"
          >
          <el-table-column prop="sequence" label="index" width="150" ></el-table-column>
          <el-table-column prop="score" label="评分" width="150" ></el-table-column>
          <el-table-column prop="receiverId" width="150" v-if="false"></el-table-column>
          <el-table-column prop="studentName" width="150" v-if="false"></el-table-column>
          <el-table-column prop="comment" width="150" v-if="false"></el-table-column>
        </el-table>
        <el-pagination
            background="true"
            layout="prev, pager, next"
            :total="total"
            v-model:currentPage="queryInfo.page"
            :page-size="queryInfo.size"
            @current-change="handlePageChange"
        />
    </el-aside>
    <el-main>
      <div class="correct-container">
        <h2>作业详情</h2>
        <el-card header="学生信息">
            <p>学号: {{ id }}</p>
            <p>姓名: {{ name }}</p>
        </el-card>
        <el-card header="标准答案">
            <p>{{ homework.standardAnswer }}</p>
        </el-card>
        <el-card header="学生答案">
            <p>{{ homework.content }}</p>
            <el-upload
                  class="upload-demo"
                  ref="upload"
                  action=""
                  :file-list="ExceList"
                  :on-preview="handlePreview"
                  :auto-upload="false">
            </el-upload>
        </el-card>
        <el-card header="批改结果">
            <input :span="6"
              prop="rateValue"
              type="number"
              v-model.number="grade.score"
              min="0"
              max="100"
              class="rateSize">
            <el-input
                prop="comment"
                v-model="grade.comment"
                :rows="2"
                type="textarea"
                placeholder="请在此输入评语"
                clearable
                class="commentSize"
            />
        </el-card>
        <el-button :span="6" type="primary" @click="saveFeedback">提交</el-button>
        <el-button :span="6" type="primary" @click="getEvaluate">下一份</el-button>
      </div>
    </el-main>
    </el-container>
    </div>
  </template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { evaluateHomework } from '@/api/evaluateHomework'
import { getCorrectHistory } from '@/api/getCorrectHistory'
import { getCount } from '@/api/getCount'
import { getSequenceHomework } from '@/api/getSequenceHomework'
import { evaluate } from '@/api/evaluate'
import { ElMessage } from 'element-plus'

const route = useRoute()

const historyData = ref([])
const total = ref(0)
const currentPage = ref(1)
const currentTime = ref('')
const id = ref('')
const name = ref('')
const count = ref()

let timer

const homework = ref({
  studentId: '',
  studentName: '',
  file: '',
  anonymous: '',
  name: '',
  number: '',
  standardAnswer: '',
  content: ''
})

const eInfo = {
  homeworkId: route.params.homeworkId
}

const queryInfo = ref({
  homeworkId: route.params.homeworkId,
  page: currentPage,
  size: 10
})

const grade = ref({
  homeworkId: route.params.homeworkId,
  receiverId: '',
  score: '',
  comment: '',
  gradeTime: ''
})

const seRequest = ref({
  homeworkId: route.params.homeworkId,
  sequence: ''
})

const key = ref({
  homeworkId: route.params.homeworkId
})

const handleRowClick = async (row, event, colum) => {
  seRequest.value.sequence = row.sequence
  seRequest.value.homeworkId = route.params.homeworkId
  const res = await getSequenceHomework(seRequest.value)
  homework.value.content = res.data.data.content
  HomeworkList.value = res.data.file.map(item => ({
    name: item.fileName,
    url: item.url
  }))
  homework.value.studentId = row.receiverId
  homework.value.studentName = row.studentName
  grade.value.score = res.data.data.score
  grade.value.comment = res.data.data.comment
  if (homework.value.anonymous === '1') {
    id.value = '匿名id'
    name.value = '匿名'
  } else {
    id.value = row.receiverId
    name.value = row.studentName
  }
}

const handlePreview = (file) => {
  window.open(file.url, '_blank')
}

const getNewEvaluate = async () => {
  const res = await getCount(key.value)
  count.value = res.data.data
  if (count.value === 0) {
    getEvaluate()
  }
  console.log(count.value)
}

const getEvaluate = async () => {
  const resKey = await getCount(key.value)
  count.value = resKey.data.data
  const res = await evaluateHomework(eInfo)
  if (res.data.code === 0) {
    ElMessage('已获得新的互评作业！')
    homework.value = res.data.data
    HomeworkList.value = res.data.file.map(item => ({
      name: item.fileName,
      url: item.url
    }))
    if (homework.value.anonymous === '1') {
      id.value = '匿名id'
      name.value = '匿名'
    } else {
      id.value = homework.value.studentId
      name.value = homework.value.name
    }
  } else {
    ElMessage('已无需新的互评作业！')
  }
  getHistory()
  grade.value.comment = ''
  grade.value.score = ''
  console.log(count.value)
}

const getHistory = async () => {
  const res = await getCorrectHistory(queryInfo.value)
  historyData.value = res.data.data.rows
  total.value = res.data.data.total
}

const handlePageChange = () => {
  getHistory()
}

const saveFeedback = async () => {
  grade.value.receiverId = homework.value.studentId
  grade.value.gradeTime = currentTime.value
  const res = await evaluate(grade.value)
  if (res.data.code === 0) {
    ElMessage.success('已成功评分')
  }
  getHistory()
}

const HomeworkList = ref([])

const getCurrentTime = () => {
  const now = new Date()
  const formattedTime = `${now.getFullYear()}-${padZero(now.getMonth() + 1)}-${padZero(now.getDate())} ${padZero(now.getHours())}:${padZero(now.getMinutes())}:${padZero(now.getSeconds())}`
  currentTime.value = formattedTime
}

const padZero = (value) => {
  return value < 10 ? `0${value}` : value
}

onMounted(getHistory)
onMounted(getNewEvaluate)

onMounted(() => {
  getCurrentTime()
  timer = setInterval(getCurrentTime, 1000)
})

onBeforeUnmount(() => {
  clearInterval(timer)
})
</script>

<style scoped>
.aside{
  width: 300px;
}
.rateSize {
    width: 100px;
    height: 30px;
    font-size: 16px;
}
.commentSize {
    margin-top: 10px;
}
</style>
